package mallindex

import (
	"context"
	"strconv"
	"strings"

	"mall/common/globalkey"
	"mall/common/jwt"
	"mall/common/resultx"
	"mall/common/utils/pointy"
	"mall/service/backend/common/utils/miniapp"
	"mall/service/backend/rpc/backendclient"
	"mall/service/forum/api/internal/svc"
	"mall/service/forum/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetSearchKeywordByIdLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 搜索词详情
func NewGetSearchKeywordByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetSearchKeywordByIdLogic {
	return &GetSearchKeywordByIdLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetSearchKeywordByIdLogic) GetSearchKeywordById(
	req *types.IDReq,
	headers *[]*types.Header,
) (resp *types.SearchKeywordInfoResp, err error) {
	if req.Id == 0 {
		return nil, resultx.NewErrCode(resultx.REUQEST_PARAM_ERROR)
	}

	userId := jwt.GetUserId(l.ctx)
	var filters []string
	filters = append(filters, "Status,equalTo:"+strconv.FormatInt(int64(globalkey.StatusEnabled), 10))
	var platformId uint32 = globalkey.ThirdPartyPlatformWechatMini
	data, err := l.svcCtx.BackendRpc.GetSearchKeywordById(l.ctx, &backendclient.BaseIdReq{
		Id:         pointy.GetPointer(req.Id),
		Filter:     pointy.GetPointer(strings.Join(filters, ";")),
		VisitorId:  pointy.GetPointer(userId),
		PlatformId: pointy.GetPointer(platformId),
	})
	if err != nil {
		return nil, err
	}

	if data == nil || data.Id == nil || *data.Id == 0 {
		return nil, resultx.NewErrCode(resultx.REUQEST_PARAM_ERROR)
	}

	var linkUrl *string
	if data.LinkType != nil && *data.LinkType == uint32(globalkey.SettingBannerLinkTypeAbsolute) { // H5 绝对路径
		linkUrl = data.LinkUrl
	} else {
		linkUrl = pointy.GetPointer(miniapp.GetLinkUrl(data.LinkType, data.ObjectType, data.ObjectId, data.LinkUrl))
	}

	return &types.SearchKeywordInfoResp{
		Data: &types.SearchKeywordInfo{
			Id:         data.Id,
			Type:       data.Type,
			Title:      data.Title,
			Sort:       data.Sort,
			LinkType:   data.LinkType,
			LinkUrl:    linkUrl,
			ObjectId:   data.ObjectId,
			ObjectType: data.ObjectType,
		},
	}, nil
}
